import akshare as ak
import matplotlib.pyplot as plt
from pyecharts import options as opts
from pyecharts.charts import Line, Tab
import numpy as np

import os


plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置字体为SimHei
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题


#print(ak.stock_board_industry_name_em().板块名称.unique())

# stock_lrb_df = ak.stock_lrb_em()
# print(stock_lrb_df)

#stock_indicator_df = ak.stock_a_indicator_lg("601628")
#print(stock_indicator_df)

#three_tables_df = ak.stock_financial_report_sina()
#print(three_tables_df)

stock_code = input("输入股票代码: ")


def create_tab_chart(symbol:str):
    market_value = ak.stock_zh_valuation_baidu(symbol=stock_code, indicator="总市值",period="近十年")
    pe_ttm = ak.stock_zh_valuation_baidu(symbol=stock_code, indicator="市盈率(TTM)",period="近十年")
    
    # 选项卡1 - 销售数据
    market_value_line = (
        Line()
        .add_xaxis(market_value["date"].to_list())
        .add_yaxis("总市值", market_value["value"].to_list(), color="#5470C6")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="总市值"),
            legend_opts=opts.LegendOpts(pos_top="10%"),
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="{value} 亿元"))
        )
    )

    pe_ttm_percent_90 = np.percentile(pe_ttm["value"], 90)
    pe_ttm_percent_70 = np.percentile(pe_ttm["value"], 70)
    pe_ttm_percent_50 = np.percentile(pe_ttm["value"], 50)
    pe_ttm_percent_30 = np.percentile(pe_ttm["value"], 30)
    pe_ttm_percent_10 = np.percentile(pe_ttm["value"], 10)

    pe_ttm = (
        Line()
        .add_xaxis(pe_ttm["date"].to_list())
        .add_yaxis("市盈率(TTM)", pe_ttm["value"].to_list(), color="#5470C6",
            markline_opts=opts.MarkLineOpts(
                data=[
                        opts.MarkLineItem(name="90% Percentile", y=pe_ttm_percent_90, linestyle_opts=opts.LineStyleOpts(color='red')),
                        opts.MarkLineItem(name="70% Percentile", y=pe_ttm_percent_70, linestyle_opts=opts.LineStyleOpts(color='origin')),
                        opts.MarkLineItem(name="50% Percentile", y=pe_ttm_percent_50, linestyle_opts=opts.LineStyleOpts(color='blue')),
                        opts.MarkLineItem(name="30% Percentile", y=pe_ttm_percent_30, linestyle_opts=opts.LineStyleOpts(color='green')),
                        opts.MarkLineItem(name="10% Percentile", y=pe_ttm_percent_10, linestyle_opts=opts.LineStyleOpts(color='black'))
                ]
           ))
        .set_global_opts(
            title_opts=opts.TitleOpts(title="市盈率(TTM)"),
            legend_opts=opts.LegendOpts(pos_top="10%"),
            yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="{value} 倍")),
        )
    )

    tab = Tab()
    tab.add(market_value_line, "总市值")
    tab.add(pe_ttm, "市盈率(TTM)")

    return tab

tab = create_tab_chart(symbol=stock_code)

tab.render(stock_code + "_valuation.html")
os.system(stock_code + "_valuation.html")